package com.hk.manager;

import cn.hutool.core.io.FileUtil;
import com.hk.config.CosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangkun
 * @date 2024/12/16 18:33
 */
@Component
@Slf4j
public class CosManager {

    @Resource
    private COSClient cosClient;
    @Resource
    private CosConfig cosConfig;

    public PutObjectResult putObject(String key, File localFile) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucket(), key, localFile);
        return cosClient.putObject(putObjectRequest);
    }

    public PutObjectResult putPictureObject(String key, File localFile) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucket(), key, localFile);
        PicOperations picOperations = new PicOperations();
        picOperations.setIsPicInfo(1);
        List<PicOperations.Rule> rules = new ArrayList<>();
        // 图片压缩（转成 webp 格式）
        String webpKey = FileUtil.mainName(key) + ".webp";
        PicOperations.Rule compressRule = new PicOperations.Rule();
        compressRule.setRule("imageMogr2/format/webp");
        compressRule.setBucket(cosConfig.getBucket());
        compressRule.setFileId(webpKey);
        rules.add(compressRule);
        // 构造处理参数
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }


    public void  deleteObject(String key) {
        cosClient.deleteObject(cosConfig.getBucket(), key);
    }


}
